<template>
  <div class="scores-management">
    <!-- 搜索和过滤区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form" >
        <el-form-item label="学期" >
          <el-select v-model="filterForm.semester" placeholder="选择学期" clearable>
            <el-option
                v-for="item in semester"
                :key="item.v"
                :label="item.label"
                :value="item.v"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程">
          <el-select v-model="filterForm.courseId" placeholder="选择课程" clearable>
            <el-option
                label="全部课程"
                :value="0"
            />
            <el-option
                v-for="item in courses"
                :key="item.courseId"
                :label="item.name"
                :value="item.courseId"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <h3>成绩列表</h3>
            <el-tag type="info">共 {{ scores.length }} 条记录</el-tag>
          </div>
          <div class="header-actions">
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>导出成绩
            </el-button>
          </div>
        </div>
      </template>

      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
      >

        <el-table-column prop="semester" label="学期">
          <template #default="scope">
            <el-tag :type="'primary'">
              <span >{{ getSemesterName(scope.row.semester) }}</span>
            </el-tag>
          </template>
        </el-table-column>
<!--        <el-table-column prop="courseId" label="课程号"/>-->
        <el-table-column prop="courseName" label="课程名称"/>
        <el-table-column prop="credit" label="学分"/>
        <el-table-column prop="type" label="课程性质">
          <template #default="scope">
            <el-tag :type="getExamTypeTag(scope.row.type)">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
<!--        <el-table-column prop="teacherName" label="任课教师名称"/>-->
        <el-table-column prop="score" label="成绩">
          <template #default="scope">
            <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="100" >
          <template #default="scope">
            <el-button link type="primary" @click="reviewDetailsScore(scope.row.courseId)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>


      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="scores.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 编辑成绩对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="成绩详情"
        width="500px"
    >
      <el-form
          ref="scoreFormRef"
          :model="scoreForm"
          label-width="100px"
      >
        <el-form-item label="学号">
          <el-input v-model="scoreForm.studentId" readonly />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="baseInfo.name" readonly />
        </el-form-item>
        <el-form-item label="学期">
          <el-input :model-value="getSemesterName(scoreForm.semester)" readonly/>
        </el-form-item>
        <el-form-item label="课程号">
          <el-input v-model="scoreForm.courseId" readonly />
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input v-model="scoreForm.courseName" readonly />
        </el-form-item>
        <el-form-item label="课程学分">
          <el-input v-model="scoreForm.credit" readonly />
        </el-form-item>
        <el-form-item label="课程性质">
          <el-input :model-value="scoreForm.type+ '课'" readonly />
        </el-form-item>
        <el-form-item label="任课教师">
          <el-input v-model="scoreForm.teacherName" readonly/>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input-number
              v-model="scoreForm.score"
              :precision="1"
              style="width: 180px"
              readonly
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, watch, onMounted} from 'vue'
import { Download} from '@element-plus/icons-vue'
import { useStudentStores } from "@/stores/studentStores.js"
import { useUserStore } from "@/stores/userStores.js"
import { storeToRefs } from "pinia";
import axios from "axios";
import baseURL from "@/config/config.js";
const { scores, courses } = storeToRefs(useStudentStores())
const { student, baseInfo } = storeToRefs(useUserStore())
const semester = [
  {label: '全部学期', v: 0},
  {label: '一年级第一学期', v: 1},
  {label: '一年级第二学期', v: 2},
  {label: '二年级第一学期', v: 3},
  {label: '二年级第二学期', v: 4},
  {label: '三年级第一学期', v: 5},
  {label: '三年级第二学期', v: 6},
  {label: '四年级第一学期', v: 7},
  {label: '四年级第二学期', v: 8},
]

// 过滤表单
const filterForm = reactive({
  semester: 0,
  courseId: 0,
})
const dialogVisible = ref(false)
// 表格数据
const loading = ref(false)
const currentPage = ref(1) // 当前页
const pageSize = ref(10) // 一页表格的展示数量
const selectedRows = ref([])
// 计算属性：分页后的数据
const tableData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return scores.value.slice(startIndex, endIndex)
})
// 处理搜索
function handleSearch(){
  loading.value = true
  axios({
    url: baseURL + '/score/get-score-by-conditions-student',
    params: {
      courseId: filterForm.courseId,
      semester: filterForm.semester,
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    }
  }).then(res => {
    currentPage.value = 1 // 重置到第一页
    scores.value = res.data.data

  }).finally(() => {
    loading.value = false
  })
}
const scoreForm = ref({
  studentId: '', // 学号
  studentName: '',
  courseName: '',
  courseId: '',
  classId: '',
  teacherId: '',
  teacherName: '',
  temp_score: 0,
  type: "专业必修",
  score: 0,
  semester: 0,
  credit: 1
})
// 处理重置
function resetForm(){
  filterForm.semester = 0
  filterForm.courseId = 0
}
// 处理编辑
const reviewDetailsScore = (cid) => {
  const sti = student.value.studentId
  console.log("学号", sti)

  axios({
    url: baseURL + '/score/get-detail-score',
    params: {
      courseId: cid,
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    }
  }).then(res => {
    console.log(res)
    dialogVisible.value = true
    scoreForm.value = res.data.data
  })
}
// 监听过滤条件变化，重置分页
watch(filterForm, () => {
  currentPage.value = 1
  selectedRows.value = []
})

// 监听分页变化，重置选择
watch([currentPage, pageSize], () => {
  selectedRows.value = []
})

// 处理表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}
// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
}
const handleCurrentChange = (val) => {
  currentPage.value = val
}
// 处理导出
const handleExport = () => {
  axios({
    url: baseURL + '/score/download',
    params: {
      courseId: filterForm.courseId,
      semester: filterForm.semester,
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    responseType: 'blob',
  }).then(res => {
    handleDownload(res.data)
  })
}
const handleDownload = (blobData) => {
  if (!blobData) return;

  // 1. 创建Blob对象（指定正确的MIME类型）
  const blob = new Blob([blobData], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel文件类型
    // 若导出CSV，改为：type: 'text/csv'
  });

  // 2. 创建临时URL
  const url = URL.createObjectURL(blob);

  // 3. 创建下载链接
  const a = document.createElement('a');
  a.href = url;

  // 4. 设置文件名（可从响应头获取或固定）
  a.download = '成绩表.xlsx'; // 固定文件名
  // 或从响应头获取（如果后端返回）：
  // a.download = getFilenameFromHeader(response.headers);

  // 5. 触发下载
  document.body.appendChild(a);
  a.click();

  // 6. 释放资源
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};
// 获取考试类型标签
const getExamTypeTag = (type) => {
  const map = {
    '专业选修': 'warning',
    '专业必修': 'danger',
    '通识选修': 'info'
  }
  return map[type] || 'info'
}
// 获取成绩样式
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}
// 获取学期名字
function getSemesterName(v){
  const it = semester.find(item => item.v === v)
  return it ? it.label : ""
}

onMounted(() => {
  scores.value = []
})
</script>

<style scoped>
.scores-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
/* 让表单元素平均分布 */
.filter-form .el-form-item {
  flex: 1;
  min-width: 200px; /* 防止元素过窄 */
  margin-right: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title h3 {
  margin: 0;
  font-size: 16px;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.el-button:focus:not(.is-focus):not(:active) {
  outline: none;
  box-shadow: none;
}
.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #e6a23c;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>